package springboot.demo.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import springboot.demo.annotation.NotProfile;
import springboot.demo.bean.Novel;
import springboot.demo.dao.NovelMapper;
import springboot.demo.service.NovelService;

@Service
@NotProfile("simple")
public class NovelServiceImpl implements NovelService {
    private static Logger LOGGER = LoggerFactory.getLogger(NovelServiceImpl.class);

    @Autowired
    NovelMapper novelMapper;

    @Override
    public Page<Novel> pageQuery(Page pageReq) {
        Page<Novel> pageRes = novelMapper.selectPage(pageReq, new LambdaQueryWrapper<Novel>());
        return pageRes;
    }

    @Override
    public List<Novel> list() {
        LOGGER.info("log in service");
        return null;
    }

    @Override
    public Novel getNovelById(int id) {
        LOGGER.info("getNovelById---id: " + id);
        return novelMapper.selectById(id);
    }

    /**
     * 外层方法没有开事务，调用内层方法的事务不生效
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public Novel testTran(int id) throws Exception {
        return incrementById(id);
    }

    /**
     * 事务默认只回滚RuntimeException异常
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Novel incrementById(int id) throws Exception {
        Novel novel = novelMapper.selectById(id);
        LOGGER.info("novel ver: {}", novel.getVer());
        novel.setVer(novel.getVer() + 1);
        novelMapper.updateById(novel);

        if (id == 1) {
            throw new RuntimeException();
        }
        if (id == 2) {
            throw new Exception("e");
        }

        return novel;
    }

    @Override
    public Novel testSqlInject(String query) {
        Novel novel = novelMapper.selectByQuery(query);
        LOGGER.info("queryed novel name:{}", novel.getNovelName());
        return novel;
    }
}
